package com.feijin.testwisdomzonedemo.ui;

import android.Manifest;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.feijin.testwisdomzonedemo.BuildConfig;
import com.feijin.testwisdomzonedemo.R;
import com.feijin.testwisdomzonedemo.actions.UserInfoAction;
import com.feijin.testwisdomzonedemo.model.AvatarDto;
import com.feijin.testwisdomzonedemo.ui.impl.InfoView;
import com.feijin.testwisdomzonedemo.util.L;
import com.feijin.testwisdomzonedemo.util.base.UserBaseActivity;
import com.feijin.testwisdomzonedemo.util.dialog.SimpleDialogUtil;
import com.feijin.testwisdomzonedemo.util.photo.PicUtils;
import com.feijin.testwisdomzonedemo.util.photo.StringUtill;
import com.lgc.garylianglib.imgDeal.utilFixSevent.PhotoFitSevent;
import com.lgc.garylianglib.util.CustomToast;
import com.lgc.garylianglib.util.base.BaseActivity;
import com.lgc.garylianglib.util.data.ResUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URLDecoder;
import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.view.KeyEvent.KEYCODE_BACK;

/**
 * <pre>
 *     author : feijin_lgc
 *     e-mail : 595184932@qq.com
 *     time   : 2018/3/22 下午6:11
 *     desc   : 测试  内容 首页
 *     version: 1.0
 * </pre>
 */
public class MainActivity extends UserBaseActivity<UserInfoAction> implements InfoView {

    @BindView(R.id.detail_webview)
    WebView mWebView;
    private ArrayList<String> loadHistoryUrls = new ArrayList<String>();


    /**
     * 头像选择弹出框
     */
    private TextView photo_tv, camera_tv;
    private Dialog dialog;
    private View inflate;
    private TextView cancel;

    private static final int REQUEST_CODE_TAKE_PHOTO = 0x110;
    private static final int REQ_PERMISSION_CODE_TAKE_PHOTO = 0X112;
    private String mCurrentPhotoPath;
    private String fileName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding(R.layout.activity_main);

    }

    /**
     * 提交头像
     */
    @Override
    public void submitAvatar() {

    }

    /**
     * 提交成功头像
     *
     * @param dto
     */
    @Override
    public void uploadAvatar(AvatarDto dto) {
        showSuccessToast("上传成功 " + dto.getData().getSrc());
    }

    @Override
    protected UserInfoAction initAction() {
        return new UserInfoAction(this);
    }

    @Override
    protected void initialize() {
        context = this;
        activity = this;
        initView();
        loadView();
    }

    @Override
    public void onError(String message, int code) {

        loadDiss();
        showErrorToast(message);
    }

    @Override
    public void onRefreshTokenSuccess() {

    }

    @Override
    public void onRefreshTokenError(String message, int code) {

    }

    protected void initView() {
        // 设置可以支持缩放
        mWebView.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        mWebView.getSettings().setBuiltInZoomControls(false);
        // 扩大比例的缩放
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.getSettings().setLayoutAlgorithm(
                WebSettings.LayoutAlgorithm.SINGLE_COLUMN);


        WebSettings webSettings = mWebView.getSettings();
        webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
        webSettings.setJavaScriptEnabled(true);// 设置支持javascript脚本

        //如果访问的页面中有Javascript，则webview必须设置支持Javascript
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setAppCacheEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);

        //在js中调用本地java方法
        mWebView.addJavascriptInterface(new JsInterface(this), "DhccWebView");


    }

    /**
     * 加载网页
     */
    protected void loadView() {

        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                L.e("test", "返回的链接：：" + url);
                /**
                 * 拦截
                 */
                try {

                    String name = URLDecoder.decode(url, "UTF-8");
                    L.e("test", "URLDecoder：：" + name);
                    if (name.contains("id")) {
                        name = name.split("\\?")[1];
                        L.e("test", "split：：" + name);

                        if (name.contains("=")) {

                            String id = name.split("=")[1];
                            Toast.makeText(MainActivity.this, "拦截 获取的ID 是" + id, Toast.LENGTH_LONG).show();
                        } else {
//                            新的方式按JOSN格式解析
                            JSONObject temp = new JSONObject(name);
                            if (temp.has("id")) {
                                String id = temp.getString("id");
                                L.e("test", "id：：" + id);

                                Toast.makeText(MainActivity.this, "拦截 获取的ID 是 " + id, Toast.LENGTH_LONG).show();
                            } else {
                                System.out.println("提示未知操作");
                            }
                        }


                        loadHistoryUrls.add(url);
                        return false;// 解析正常就跳转到订单界面，其它按钮则跳转网页
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                    // 异常就跳转新网页
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    // 异常就跳转新网页
                }
                loadHistoryUrls.add(url);
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
//                loadDiss();
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
//                loadDiss();
//                loadError("加载失败...");
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient() {

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                        String acceptType) {
//                mUploadMessage = uploadMsg;
//                startActivityForResult(createDefaultOpenableIntent(),
//                        FILECHOOSER_RESULTCODE);
            }

            // For Android 4.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                        String acceptType, String capture) {
//                mUploadMessage = uploadMsg;
//                startActivityForResult(createDefaultOpenableIntent(),
//                        FILECHOOSER_RESULTCODE);

            }

            @Override
            public boolean onJsAlert(WebView view, String url, String message,
                                     final JsResult result) {
                AlertDialog.Builder b2 = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("温馨提示")
                        .setMessage(message)
                        .setPositiveButton("确认",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        result.confirm();
                                    }
                                });
                b2.setCancelable(false);
                b2.create();
                b2.show();
                return true;
            }

            @Override
            public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("JsConfirm")
                        .setMessage(message)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.confirm();
                            }
                        })
                        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                result.cancel();
                            }
                        })
                        .setCancelable(false)
                        .show();
                return true;
            }
        });
//        mWebView.loadUrl("http://fandomschool.cn/store/wap2/index.html");


        mWebView.loadUrl("file:///android_asset/demo.html");
    }

    /**
     * 处理 js 事件
     */
    private class JsInterface {
        private Context mContext;

        public JsInterface(Context context) {
            this.mContext = context;
        }

        /**
         * 扫码
         */
        @JavascriptInterface
        public void scanQCode() {
            cbScanQCode("测试返回 123456");
        }

        /**
         * 打开照相机
         */
        @JavascriptInterface
        public void openCamera() {
            takePhotoNoCompress();
        }

        /**
         * 打开 相册
         */
        @JavascriptInterface
        public void openGallery(int name) {
            picPhoto();
        }

        /**
         * 打开 获取定位
         */
        @JavascriptInterface
        public void getLocation() {
            showInfoToast("js  获取定位");
        }

        /**
         * 打开 获取步数
         */
        @JavascriptInterface
        public void getStep() {
            cbGetStep("99999");
        }

        /**
         * 打开 订单支付
         */
        @JavascriptInterface
        public void orderPay(String id, double price, String remark) {
            showInfoToast("js  支付  id ：" + id + " price " + price + " remark " + remark);
            cbOrderPay(1);
        }

        /**
         * 打开 提示
         */
        @JavascriptInterface
        public void showToast(String obj) {
            showInfoToast(obj);
        }

        /**
         * 打开 提示
         */
        @JavascriptInterface
        public void showAlert(String title, String msg) {
            SimpleDialogUtil.showSimpleDialog(activity, title, msg, null, new SimpleDialogUtil.OnClickConfirmListener() {
                @Override
                public void onClickConfirmListener(View view) {
                    SimpleDialogUtil.disMissDialog();
                    cbShowConfirm();
                }
            });

        }

        /**
         * 打开 提示
         */
        @JavascriptInterface
        public void showConfirm(String title, String msg) {
            SimpleDialogUtil.showSimpleDialog(activity, title, msg, new SimpleDialogUtil.OnClickCancelListener() {
                @Override
                public void onClickCancalListener(View view) {
                    SimpleDialogUtil.disMissDialog();
                }
            }, new SimpleDialogUtil.OnClickConfirmListener() {
                @Override
                public void onClickConfirmListener(View view) {
                    SimpleDialogUtil.disMissDialog();
                    cbShowConfirm();
                }
            });
        }

        /**
         * 打开 获取设备信息
         */
        @JavascriptInterface
        public void getDeviceInfo() {
            showInfoToast("获取设备信息");

            cbGetDeviceInfo(getPhoneBrand() + " " + getPhoneModel());
        }

        /**
         * 打开 关闭界面
         */
        @JavascriptInterface
        public void closePage() {
            showInfoToast("关闭界面");
            System.exit(0);

        }

        /**
         * 打开 打开H5页面
         */
        @JavascriptInterface
        public void openLocalWeb(String url) {
            Intent intent = new Intent(context, WebViewActivity.class);
            intent.putExtra("URL", url);
            startActivity(intent);


        }

        /**
         * 打开 打开原生页面
         */
        @JavascriptInterface
        public void openNativePage(String name) {
            showInfoToast("打开原生页面");
            jumpActivityNotFinish(context, TestActivity.class);
        }

        /**
         * 打开 拨打电话
         */
        @JavascriptInterface
        public void callPhone(String number) {
            final String phone = number;
            SimpleDialogUtil.showSimpleDialog(MainActivity.this, ResUtil.getString(R.string.dialog_tip), "是否拨打 " + number, new SimpleDialogUtil.OnClickCancelListener() {
                @Override
                public void onClickCancalListener(View view) {
                    SimpleDialogUtil.disMissDialog();
                }
            }, new SimpleDialogUtil.OnClickConfirmListener() {
                @Override
                public void onClickConfirmListener(View view) {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent.setData(data);
                    startActivity(intent);
                    SimpleDialogUtil.disMissDialog();
                }
            });

        }

        /**
         * 打开 上传文件
         */
        @JavascriptInterface
        public void uploadFile(String url, String url2) {
            showInfoToast("url " + url + " url2 " + url2);
            cbUploadFile(1);
        }
    }

    /**
     * 获取手机品牌
     *
     * @return
     */
    public static String getPhoneBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取手机型号
     *
     * @return
     */
    public static String getPhoneModel() {
        return android.os.Build.MODEL;
    }

    /**
     * 返回  二维码扫描结果为
     */
    public void cbScanQCode(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("javascript:cbScanQCode('" + msg + "')");
            }
        });
    }

    /**
     * 返回  拍照后的图片地址为
     */
    public void cbOpenCamera(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("javascript:cbOpenCamera('" + msg + "')");
            }
        });
    }

    /**
     * 返回  打开相册后的图片地址为
     */
    public void cbOpenGallery(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("javascript:cbOpenGallery('" + msg + "')");
            }
        });
    }

    /**
     * 返回  步数为
     */
    public void cbGetStep(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("javascript:cbGetStep('" + msg + "')");
            }
        });
    }

    /**
     * 返回  支付结果为
     */
    public void cbOrderPay(final int status) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("javascript:cbOrderPay('" + status + "')");
            }
        });
    }

    /**
     * 返回  点击了确定
     */
    public void cbShowConfirm() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("javascript:cbShowConfirm()");
            }
        });
    }

    /**
     * 返回  硬件信息为
     */
    public void cbGetDeviceInfo(final String obj) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("javascript:cbGetDeviceInfo('" + obj + "')");
            }
        });
    }

    /**
     * 返回  上传结果为
     */
    public void cbUploadFile(final int status) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl("javascript:cbUploadFile('" + status + "')");
            }
        });
    }

    /**
     * 点击换头像
     */
    private void showSelectDiaLog() {
        dialog = new Dialog(this, R.style.MY_AlertDialog);
        dialog.setCanceledOnTouchOutside(true);
        inflate = LayoutInflater.from(this).inflate(R.layout.dialog_head_layout, null);
        cancel = (TextView) inflate.findViewById(R.id.btn_cancel);
        camera_tv = ((TextView) inflate.findViewById(R.id.camera_tv));
        photo_tv = ((TextView) inflate.findViewById(R.id.photo_tv));
        camera_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                takePhotoNoCompress();
                dialog.dismiss();
            }
        });
        photo_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                picPhoto();
                dialog.dismiss();
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.setContentView(inflate);
        Window dialogWindow = dialog.getWindow();
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.y = 20;
        dialogWindow.setAttributes(lp);
        dialog.show();
    }
/**--------------------拍照-------------**/


    /**
     * 拍照准备（需要判断是否有权限）
     */
    public void takePhotoNoCompress() {
        boolean b = ContextCompat.checkSelfPermission(this,
                Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED;//判断是否有写的权限
        if (b) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},//获取照片权限
                    REQ_PERMISSION_CODE_TAKE_PHOTO);
        } else {
            fileName = getFileName() + ".jpg";
            mCurrentPhotoPath = PhotoFitSevent.takePhotoNoCompress(this);
        }
    }

    /**
     * 从相册获取图片
     */
    public void picPhoto() {
        boolean b = ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED;//判断是否有写的权限
        if (b) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE},//获取照片权限
                    REQUEST_CODE_TAKE_PHOTO);
        } else {
            fileName = getFileName() + ".jpg";

            PhotoFitSevent.takePhoto(this);
        }
    }

    /**
     * 权限获取结果
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQ_PERMISSION_CODE_TAKE_PHOTO:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    fileName = getFileName() + ".jpg";
                    ;
                    mCurrentPhotoPath = PhotoFitSevent.takePhotoNoCompress(this);//获取权限成功后再起请求拍照功能
                } else {
                    // Permission Denied
                    showErrorToast(ResUtil.getString(R.string.photo_permission));
                }
                break;
            case REQUEST_CODE_TAKE_PHOTO:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    fileName = getFileName() + ".jpg";
                    ;
                    PhotoFitSevent.takePhoto(this);//获取权限成功后再起请求拍照功能
                } else {
                    // Permission Denied
                    //
                    showErrorToast(ResUtil.getString(R.string.photo_permission));
                }
                break;
        }

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        com.lgc.garylianglib.util.L.e("fileName", "----------------------->" + fileName + "data" + data);
        com.lgc.garylianglib.util.L.e("resultCode" + resultCode + "  requestCode " + requestCode);
        switch (requestCode) {
            case PhotoFitSevent.REQUEST_CODE_TAKE_PHOTO:
                getPhotoDir(mCurrentPhotoPath);
                break;
            case PhotoFitSevent.SELECT_PIC_BY_PICK_PHOTO:
                if (data != null) {
                    if (Build.VERSION.SDK_INT >= 19) {
                        //4.4 及以上系统使用这个方法处理图片
                        getPhotoDir(PhotoFitSevent.handleImageOnKitKat(data, this));
                        return;
                    }
                    //4.4 及以下系统使用这个方法处理图片
                    getPhotoDir(PhotoFitSevent.handleImageBeforeKitKat(data, this));
                }

                break;
            case PhotoFitSevent.SELECT_CUT_PICK_PHOTO://剪裁图片
                try {

                    if (data != null) {
                        File imgUri = new File(fileName);
                        Uri dataUri = FileProvider.getUriForFile
                                (this, BuildConfig.APPLICATION_ID + ".android7.fileprovider", imgUri);
                        int zoomSacle = 3;
                        try {
                            // 当图片大小大于512kb至少缩小两倍
                            if (imgUri.length() / 1024 > 512) {
                                zoomSacle = zoomSacle * 10;
                            }
                            PicUtils.showCutPhoto(data, zoomSacle, imgUri.getPath());
                            if (isShowFilePic(imgUri)) {
                                loadDialog(ResUtil.getString(R.string.main_process));
                                baseAction.uploadAvatar(fileName);
                            }
                        } catch (FileNotFoundException e) {
                            System.out.println(e.toString());
                            CustomToast.showToasts(context, R.string.error);
                        }
                    } else {
                        com.lgc.garylianglib.util.L.e("ffl", "onActivityResult: -------------intent为null------------");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    /**
     * 是否显示到图片
     */
    public boolean isShowFilePic(File file) {
        boolean exists = file.exists();
        return exists;
    }

    /**
     * 获取路径
     *
     * @param s
     */
    private void getPhotoDir(String s) {
        fileName = s;//截取最后一段图片


        File file = new File(s);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            PicUtils.showPicToCutPhoto2(file, this);
        } else {
            PicUtils.showPicToCutPhoto(Uri.fromFile(file), this);
        }


    }

    /**
     * 头像设置选择窗口
     */

    private static String getFileName() {
        return "feijin" + "_" + StringUtill.getTimeName();
    }

    @Override
    protected void onResume() {
        super.onResume();
        baseAction.toRegister();
    }

    @Override
    protected void onStop() {
        super.onStop();
        hideInput();
        baseAction.toUnregister();
    }

    /**
     * 返回按钮事件
     *
     * @param keyCode
     * @param event
     * @return
     */
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KEYCODE_BACK:
                if (loadHistoryUrls.size() > 1) {
                    loadHistoryUrls.remove(loadHistoryUrls.size() - 1);
                    mWebView.goBack();
                    return true;
                }
                System.exit(0);
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
